<template>
  <div class="main">
    <div class="wrapper">
      <Rated />
      <!-- <p>{{ count }}</p> -->
      <Movies @addBs="addBs" :moreList="moreList" />
    </div>
  </div>
</template>

<script>
import Rated from "./components/Rated.vue";
import Movies from "./components/Movies.vue";

import BScroll from "better-scroll";

export default {
  data() {
    return {
      count: 1,
      moreList: [],
      ids: [], // 用于存储所有的id
      startIndex: 0,
      length: 10,
      timer: null,
    };
  },
  components: {
    Rated,
    Movies,
  },
  mounted() {
    // this.timer = setInterval(() => {
    //   this.count++;
    // }, 1000);
  },
  // 当keep-alive的缓存组件显示在页面上时调用
  activated() {
    console.log(123);
    this.timer = setInterval(() => {
      this.count++;
    }, 1000);
  },
  // 当keep-alive的缓存组件隐藏时调用
  deactivated() {
    console.log(456);
    clearInterval(this.timer);
  },
  // beforeUnmount() {
  //   console.log(123);
  // },
  methods: {
    addBs(ids, length) {
      this.ids = ids;
      this.startIndex = length;

      const bs = new BScroll(".main", {
        startY: 0,
        scrollX: false,
        scrollY: true,
        click: true,
        pullUpLoad: true, // 允许页面进行上拉加载
      });

      bs.on("pullingUp", () => {
        console.log("拉到低了");
        // bs.finishPullUp()

        // 这里已经是拉到底了，再一次去请求接口

        // http://101.35.148.193:3000/api/movies/more
        // post
        // ids: 电影的id，如果有多个，那么用逗号隔开

        fetch("http://101.35.148.193:3000/api/movies/more", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            // ids: "1250604,1499719",
            // ids: this.ids.join(","),
            ids: this.ids
              .slice(this.startIndex, this.startIndex + this.length)
              .join(","),
          }),
        })
          .then((response) => response.json())
          .then((res) => {
            // console.log(res);
            if (res.success) {
              // 要将加载更多得到的数据拼接到原来的数组中，而不是替换
              this.moreList = [...this.moreList, ...res.data];
              // console.log(this.moreList);
              this.startIndex += res.data.length;
              // console.log(this.startIndex);

              setTimeout(() => {
                bs.refresh(); // 重新生成一次滚动的效果
                bs.finishPullUp(); // 用来告诉bs，这一次的请求好了，可以准备下一次的下拉到底的事件了
              }, 0);
            }
          });
      });
    },
  },
};
</script>

<style lang="less">
.main {
  // margin-top: 98px;
  // margin-bottom: 49px;
  position: fixed;
  top: 98px;
  bottom: 49px;
  left: 0;
  right: 0;
  overflow: hidden;
}
</style>
